<?php
class Cellphonezone_Productshipping_Helper_Data extends Mage_Core_Helper_Abstract{

    protected $_checkout = null;
    protected $_quote    = null;
    protected $_address = array();
   public function getAddress()
    {
        if (empty($this->_address)) {
            $this->_address = $this->getQuote()->getShippingAddress();
        }
        return $this->_address;
    }
    public function getCheckout()
    {
        if (null === $this->_checkout) {
            $this->_checkout = Mage::getSingleton('checkout/session');
        }
        return $this->_checkout;
    }

    /**
     * Get active quote
     *
     * @return Mage_Sales_Model_Quote
     */
    public function getQuote()
    {
        if (null === $this->_quote) {
            $this->_quote = $this->getCheckout()->getQuote();
        }
        return $this->_quote;
    }
   
    public function getProduct(){
      return  Mage::registry('current_product');
    }

    public function getProductDefaultQty($product = null)
    {
        if (!$product) {
            $product = $this->getProduct();
        }

        $qty = $this->getMinimalQty($product);
        $config = $product->getPreconfiguredValues();
        $configQty = $config->getQty();
        if ($configQty > $qty) {
            $qty = $configQty;
        }

        return $qty;
    }
    public function getMinimalQty($product)
    {
        if ($stockItem = $product->getStockItem()) {
            return ($stockItem->getMinSaleQty() && $stockItem->getMinSaleQty() > 0 ? $stockItem->getMinSaleQty() * 1 : null);
        }
        return null;
    } 
    public function getCountryId()
    {
        $countryId =  $this->getAddress()->getCountryId();
        if (is_null($countryId)) {
            $countryId = Mage::helper('core')->getDefaultCountry();
        }
        return $countryId;
    }   
    public function getEstimatePostcode()
    {
        return $this->getAddress()->getPostcode();
    }
   public function getEstimateCity()
    {
        return $this->getAddress()->getCity();
    }

    public function getEstimateRegionId()
    {
        return $this->getAddress()->getRegionId();
    }

    public function getEstimateRegion()
    {
        return $this->getAddress()->getRegion();
    } 
    /**
     * Sort rates recursive callback
     *
     * @param array $a
     * @param array $b
     * @return int
     */
    protected function _sortRates($a, $b)
    {
        if ((int)$a[0]->carrier_sort_order < (int)$b[0]->carrier_sort_order) {
            return -1;
        }
        elseif ((int)$a[0]->carrier_sort_order > (int)$b[0]->carrier_sort_order) {
            return 1;
        }
        else {
            return 0;
        }
    }
    public function getRates(){
   
       // $productId  = (int) $this->getRequest()->getParam('id');
        $country    = (string) $this->_getRequest()->getParam('country_id');
        $postcode   = (string) $this->_getRequest()->getParam('estimate_postcode');
        $city       = (string) $this->_getRequest()->getParam('estimate_city');
        $regionId   = (string) $this->_getRequest()->getParam('region_id');
        $region     = (string) $this->_getRequest()->getParam('region');
        
        if(!$postcode){
          $postcode = $this->getEstimatePostcode();
        }
        if(!$city){
          $city = $this->getEstimatePostcode();
        }
        if(!$regionId){
          $regionId = $this->getEstimateRegionId();
        }
        if(!$region){
          $region = $this->getEstimateRegion();
        }

        if($country){
           
         $this->getQuote()->getShippingAddress()
        ->setCountryId($country)
        ->setCity($city)
        ->setPostcode($postcode)
        ->setRegionId($regionId)
        ->setRegion($region)
        ->setCollectShippingRates(true);
        $this->getQuote()->save();
        }
        
        if(!$country){
           $country = $this->getCountryId();
        }
        //$country = 'US';
       // $productId = 147;
        $qty = (string) $this->_getRequest()->getParam('qty');
        if(!$qty){
         $qty = $this->getProductDefaultQty(); 
        }
        //   $product =  Mage::getModel('catalog/product')->load($productId);
        $product = $this->getProduct();
        $request = new Varien_Object();
        $request->setQty($qty);
        $item = Mage::getModel('sales/quote')->addProduct($product, $request);
        /** @var $request Mage_Shipping_Model_Rate_Request */
        $request = Mage::getModel('shipping/rate_request');
        $request->setAllItems( array($item));
        $request->setDestCountryId($country);
        $request->setDestRegionId($regionId);
        $request->setDestRegionCode($region);
        /**
         * need to call getStreet with -1
         * to get data in string instead of array
         */
        //$request->setDestStreet($this->getStreet(-1));
        //  $request->setDestCity($city);
        $request->setDestPostcode($postcode);
       // $request->setPackageValue($item ? $item->getBaseRowTotal() : $this->getBaseSubtotal()); 
       // $request->setPackageValueWithDiscount($packageValueWithDiscount);
        $request->setPackageWeight($item->getWeight());
        $request->setPackageQty($item->getQty());

        /**
         * Need for shipping methods that use insurance based on price of physical products
         */
        // $packagePhysicalValue = $item
        //    ? $item->getBaseRowTotal()
        // : $this->getBaseSubtotal() - $this->getBaseVirtualAmount();
         //$request->setPackagePhysicalValue($packagePhysicalValue);

        //  $request->setFreeMethodWeight($item ? 0 : $this->getFreeMethodWeight());

        /**
         * Store and website identifiers need specify from quote
         */
        /*$request->setStoreId(Mage::app()->getStore()->getId());
        $request->setWebsiteId(Mage::app()->getStore()->getWebsiteId());*/

        $request->setStoreId(Mage::app()->getStore()->getId());
        $request->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
        //$request->setFreeShipping($this->getFreeShipping());
        /**
         * Currencies need to convert in free shipping
         */
        $request->setBaseCurrency(Mage::app()->getStore()->getBaseCurrency());
        $request->setPackageCurrency(Mage::app()->getStore()->getCurrentCurrency());
        //$request->setLimitCarrier($this->getLimitCarrier());

        $result = Mage::getModel('shipping/shipping')->collectRates($request)->getResult();
        $shippingRateCollection = array();  

        if ($result) {
            $shippingRates = $result->getAllRates();
            foreach ($shippingRates as $shippingRate) {
                $rate = Mage::getModel('sales/quote_address_rate')
                    ->importShippingRate($shippingRate);
                $shippingRateCollection[] = $rate;
            }
        }
        $groups = array(); 
        foreach( $shippingRateCollection as  $rate ){

            if (!$rate->isDeleted() && $rate->getCarrierInstance()) {
                if (!isset($groups[$rate->getCarrier()])) {
                    $groups[$rate->getCarrier()] = array();
                }
                // echo $rate->getCode(),'||',$rate->getMethodTitle(),'||',$rate->getPrice().'<br/>';
                $groups[$rate->getCarrier()][] = $rate;
                $groups[$rate->getCarrier()][0]->carrier_sort_order = $rate->getCarrierInstance()->getSortOrder();
            }


        }
        uasort($groups,array($this,'_sortRates'));
        $data = array('country_id' => $country, 'region_id' =>$regionId);      
        Mage::helper('deliveryzone')->setLocation($data);
        $zone = Mage::getModel('deliveryzone/zone')->setType(MageWorx_DeliveryZone_Model_Zone::ZONE_TYPE_SHIPPINGMETHOD);
        $carriers = $zone->getByLocation(Mage::helper('deliveryzone')->getLocation());
        $_rates = array();
        if (count($carriers)) {
            foreach ($carriers as $code => $methods) {
                if (is_array($carriers[$code])) {
                    $carriers[$code] += explode(',', $methods);
                } else {
                    $carriers[$code] = explode(',', $methods);
                }
            }

            foreach ($groups as $code => $rates) {
                if (empty($carriers[$code])) {
                   // continue;
                }
                foreach ($rates as $rate) {
                    if (!in_array($rate->getMethod(), $carriers[$code])) {
                       // continue;
                    }
                    $_rates[$code][] = $rate;
                     //echo $rate->getCode(),'||',$rate->getMethodTitle(),'||',$rate->getPrice().'<br/>';
                }
            }
           
        } else {
            //return $this->_rates = $groups;
        }
        return $_rates;

   
   } 
}
